﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DotNet.Data;
using DotNet.Helper;

namespace ReStart
{
    class Program
    {
        private const string ProcessName = "BusRealtime";

        static void Main(string[] args)
        {
            while (true)
            {
                Core();
            }
        }

        private static void Core()
        {
            Console.WriteLine("检测实时数据变化服务已启动...");
            while (true)
            {
                var sql = @"
                            select count(1) from daolizhan
                             where busselfid in
                                   (select busselfid
                                      from (select busselfid, (sysdate - sj) * 24 * 60 * 60 c
                                              from daolizhan)
                                     where c <= 120)";
                try
                {
                    using (var db = new Database())
                    {
                        var rows = db.ExecuteScalar<int>(sql);//超过两分的数据
                        if (rows == 0)
                        {
                            //超过两分钟没有接收到数据
                            //重启
                            Console.WriteLine($"{DateTimeHelper.FormatDateHasSecond(DateTime.Now)} -> 超过两分钟没有接收到数据,重启系统");
                            LogHelper.Log("超过两分钟没有接收到数据,重启系统");
                            Kill();
                            Start();
                        }
                        else
                        {
                            Console.WriteLine($"{DateTimeHelper.FormatDateHasSecond(DateTime.Now)} -> 正常接收数据");
                            LogHelper.Log("正常接收数据");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("检测实时数据变化异常:" + e.Message);
                }
                Thread.Sleep(60000);
            }
        }

        private static void Start()
        {
            Kill();
            Process.Start($"{ProcessName}.exe");
        }

        private static void Kill()
        {
            Process[] processes = Process.GetProcessesByName(ProcessName);
            foreach (Process p in processes)
            {
                if (ProcessName == p.ProcessName)
                {
                    p.Kill();
                    p.Close();
                }
            }
        }
    }
}
